﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections;
using grproLib;
using log4net;

namespace DealPrint
{
    /// <summary>
    /// 处理报表与类之间的数据交互
    /// </summary>
    public class ReportDealClass<T> where T : class
    {
        /// <summary>
        /// 日志
        /// </summary>
        public static ILog Log = LogManager.GetLogger("ReflectionLayout");

        //存放报表字段
        private Dictionary<string, grproLib.IGRField> dicFieldList = null;
        //private Dictionary<string, IGRParameter> dicParameterList = null;
        //区分字段和参数
        private ArrayList arrayParameters = null;
        private ArrayList arrayFields = null;
        //private IGRFieldBox KDosageAmt;
        //private IGRColumnContentCell PAmountContentCell;

        //private grproLib.IGRField DrugAmtField;  //药品数量(整的)
        //private grproLib.IGRField DrugActAmtField; //药品数量(实际带小数的)

        public List<T> DataModel { get; set; }
        public grproLib.GridppReport Report { get; set; }

        public ReportDealClass(List<T> dm, grproLib.GridppReport rp)
        {
            this.DataModel = dm;
            this.Report = rp;

            //获取T中的属性值
            PropertyInfo[] propList = typeof(T).GetProperties();
            if (propList.Length > 0)
            {
                //区别报表的参数和字段
                arrayFields = new ArrayList();
                arrayParameters = new ArrayList();
                foreach (PropertyInfo item in propList)
                {
                    string propName = item.Name;
                    var field = this.Report.FieldByName(propName);
                    if (field != null)
                    {
                        arrayFields.Add(propName);
                    }
                    else
                    {
                        arrayParameters.Add(propName);
                    }
                    //if (propName == "Dosage")
                    //{
                    //    KDosageAmt = Report.ControlByName("FieldDosage").AsFieldBox;
                    //}
                }
            }
        }

        private void ReportSectionFormat(IGRSection Section)
        {
            if (Section.Visible)
            {
                try
                {
                    //if (KDosageAmt != null)
                    //{
                    //    if (DrugActAmtField.AsFloat != DrugAmtField.AsFloat)
                    //    {
                    //        KDosageAmt.BorderWidth = 2;
                    //        KDosageAmt.BorderStyles = GRBorderStyles.grbsDrawLeft | GRBorderStyles.grbsDrawRight | GRBorderStyles.grbsDrawTop | GRBorderStyles.grbsDrawBottom;

                    //        var LabelNoField = Report.FieldByName("LabelNo");
                    //        var DrugNameField = Report.FieldByName("DrugName");
                    //        Log.Debug($"【DealPrint】[{LabelNoField.AsString}]药品[{DrugNameField.AsString}]数量不一致 AMT[{DrugAmtField.AsFloat}]ActAmt[{DrugActAmtField.AsFloat}]");
                    //    }
                    //    else
                    //    {
                    //        KDosageAmt.BorderStyles = 0;
                    //        KDosageAmt.BorderWidth = 0;
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    Log.Error($"【DealPrint】{ex.Message} {ex.StackTrace}");
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dm"></param>
        /// <param name="rp"></param>
        public ReportDealClass(T dm, grproLib.GridppReport rp)
        {
            List<T> temp = new List<T>();
            temp.Add(dm);

            this.DataModel = temp;
            this.Report = rp;

            //获取T中的属性值
            PropertyInfo[] propList = typeof(T).GetProperties();
            if (propList.Length > 0)
            {
                //区别报表的参数和字段
                arrayFields = new ArrayList();
                arrayParameters = new ArrayList();
                foreach (PropertyInfo item in propList)
                {
                    string propName = item.Name;
                    var field = this.Report.FieldByName(propName);
                    if (field != null)
                    {
                        arrayFields.Add(propName);
                    }
                    else
                    {
                        arrayParameters.Add(propName);
                    }
                }
            }
        }

        /// <summary>
        /// 填充字段数据
        /// </summary>
        void Report_FetchRecord()
        {
            //循环加载数据
            foreach (T item in DataModel)
            {
                Report.DetailGrid.Recordset.Append();
                FillRecord(item);
                Report.DetailGrid.Recordset.Post();
            }
        }

        private void FillRecord(T model)
        {
            foreach (string fieldName in arrayFields)
            {
                grproLib.IGRField currentField = dicFieldList[fieldName];

                //if (fieldName == "DrugAMT")
                //{
                //    DrugAmtField = dicFieldList["DrugAMT"];
                //    object amt = typeof(T).GetProperty("DrugAMT").GetValue(model, null);
                //    DrugAmtField.AsString = amt != null ? amt.ToString() : "";
                //}
                //else if (fieldName == "DrugActAmt")
                //{
                //    DrugActAmtField = dicFieldList["DrugActAmt"]; ;
                //    object actAmt = typeof(T).GetProperty("DrugActAmt").GetValue(model, null);
                //    DrugActAmtField.AsString = actAmt != null ? actAmt.ToString() : "";
                //}
                //else
                //{
                object fieldValue = typeof(T).GetProperty(fieldName).GetValue(model, null);

                currentField.AsString = fieldValue != null ? fieldValue.ToString() : "";
                //}
            }

            //foreach (string ParameterName in arrayParameters)
            //{
            //    IGRParameter currentParameter = dicParameterList[ParameterName];
            //    object ParameterValue = typeof(T).GetProperty(ParameterName).GetValue(model, null);
            //    currentParameter.AsString = ParameterValue != null ? ParameterValue.ToString() : "";
            //}
        }

        //private void ReportSectionFormat(IGRSection Section)
        //{
        //    if (Section.Visible)
        //    {
        //        Boolean FontUnderline;
        //        //string s = MedUsageField.ToString();
        //        //if (MedUsageField.ToString().Contains("("))
        //        //{
        //        FontUnderline = true;
        //        //}

        //        //else
        //        //{
        //        //    FontUnderline = false;
        //        //}

        //        PAmountContentCell.Font.Underline = FontUnderline;

        //    }
        //}

        /// <summary>
        /// 报表初始化
        /// </summary>
        void Report_Initialize()
        {
            //初始化字段
            dicFieldList = new Dictionary<string, grproLib.IGRField>();
            foreach (string field in arrayFields)
            {
                grproLib.IGRField reportField = Report.FieldByName(field);
                dicFieldList.Add(field, reportField);
            }

            //dicParameterList = new Dictionary<string, IGRParameter>();
            //foreach (string Parameter in arrayParameters)
            //{
            //    IGRParameter reportParameter = Report.ParameterByName(Parameter);
            //    dicParameterList.Add(Parameter, reportParameter);
            //}
        }

        /// <summary>
        /// 报表打印
        /// </summary>
        public bool ReportPrint(bool showPrintDialog)
        {
            if (DataModel.Count <= 0 || Report == null)
            {
                return false;
            }

            try
            {
                //添加处理委托
                Report.Initialize += new grproLib._IGridppReportEvents_InitializeEventHandler(Report_Initialize);
                Report.FetchRecord += new grproLib._IGridppReportEvents_FetchRecordEventHandler(Report_FetchRecord);
                Report.SectionFormat += new _IGridppReportEvents_SectionFormatEventHandler(ReportSectionFormat);

                //处理参数内容的填充
                T firstData = DataModel[0];
                Type typeT = typeof(T);
                foreach (string parameter in arrayParameters)
                {
                    object value = typeT.GetProperty(parameter).GetValue(firstData, null);
                    var para = Report.ParameterByName(parameter);
                    if (para != null)
                    {
                        ((grproLib.IGRParameter)para).AsString = value == null ? "" : value.ToString();
                    }
                }
                //Report.PrepareRecordset();
                Report.Print(showPrintDialog);
                //Report.PrintPreview(true);

                Report.Initialize -= new grproLib._IGridppReportEvents_InitializeEventHandler(Report_Initialize);
                Report.FetchRecord -= new grproLib._IGridppReportEvents_FetchRecordEventHandler(Report_FetchRecord);
                Report.SectionFormat -= new _IGridppReportEvents_SectionFormatEventHandler(ReportSectionFormat);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 报表打印
        /// </summary>
        public bool ReportPrintPreview(bool ShowDialog)
        {
            if (DataModel.Count <= 0 || Report == null)
            {
                return false;
            }

            try
            {
                //添加处理委托
                Report.Initialize += new grproLib._IGridppReportEvents_InitializeEventHandler(Report_Initialize);
                Report.FetchRecord += new grproLib._IGridppReportEvents_FetchRecordEventHandler(Report_FetchRecord);
                Report.SectionFormat += new _IGridppReportEvents_SectionFormatEventHandler(ReportSectionFormat);

                //处理参数内容的填充
                T firstData = DataModel[0];
                Type typeT = typeof(T);
                foreach (string parameter in arrayParameters)
                {
                    object value = typeT.GetProperty(parameter).GetValue(firstData, null);
                    var para = Report.ParameterByName(parameter);
                    if (para != null)
                    {
                        ((grproLib.IGRParameter)para).AsString = value == null ? "" : value.ToString();
                    }
                }

                if (ShowDialog)
                {
                    Report.PrintPreview(false);
                }
                else
                {
                    Report.Print(false);
                }

                Report.Initialize -= new grproLib._IGridppReportEvents_InitializeEventHandler(Report_Initialize);
                Report.FetchRecord -= new grproLib._IGridppReportEvents_FetchRecordEventHandler(Report_FetchRecord);
                Report.SectionFormat -= new _IGridppReportEvents_SectionFormatEventHandler(ReportSectionFormat);

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
